/**
 * RenderTarget implemenation
 */

#include "RenderTarget.h"

GLenum RenderTarget::_buffers[] = {
	GL_COLOR_ATTACHMENT0_EXT,
	GL_COLOR_ATTACHMENT1_EXT,
	GL_COLOR_ATTACHMENT2_EXT,
	GL_COLOR_ATTACHMENT3_EXT,
	GL_COLOR_ATTACHMENT4_EXT };

/////////////////////////////////////////////////

void RenderTarget::attachTexture(const TexturePtr& t)
{
	assert(t != 0);
	GLenum where = _buffers[_textures.size()];
	_textures.push_back(t);
	assert(_textures.size() <= 5);
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, _glName);
	glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, where, t->getTarget(), t->getGLName(), 0);
	assert(checkFBO());
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
	checkGLError();
}

/////////////////////////////////////////////////

void RenderTarget::attachRenderbuffer(const RenderbufferPtr& rb)
{
	assert(rb != 0);
	_renderbuffers.push_back(rb);
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, _glName);
    glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, rb->getTarget(), GL_RENDERBUFFER_EXT, rb->getGLName());
	assert(checkFBO());
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
	checkGLError();
}
/////////////////////////////////////////////////

void RenderTarget::bind()
{
	// TODO avoid rebinding
	assert(_glName);
	// TODO get MRT working for Float textures, if possible
	assert(_textures.size() == 1);
	glGetIntegerv(GL_DRAW_BUFFER, &_savedDrawBuffer);
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, _glName);
	glDrawBuffers(_textures.size(), _buffers);
	assert(checkFBO());
	checkGLError();
}

/////////////////////////////////////////////////

void RenderTarget::unbind()
{
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
	glDrawBuffer(_savedDrawBuffer);
	checkGLError();
}

/////////////////////////////////////////////////

bool RenderTarget::checkFBO()
{
	GLenum status;                                            
	status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
	return (status == GL_FRAMEBUFFER_COMPLETE_EXT);
}


